<?php

class FilmController extends BackEndController {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index', 'view', 'create', 'update', 'admin', 'delete'),
                'roles' => array('admin'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Film;
        $countries = Country::model()->findAll("status=1");
        $actors = Actor::model()->findAll("status=1");
        $directors = Director::model()->findAll("status=1");
        $genres = Menu::model()->findAll('parent_id >0 and status=1');
        $tags = Tag::model()->findAll("status=1");
        $filmgenre = new FilmGenre();
        $listactor = array();
        foreach ($actors as $a) {
            $listactor[] = $a->name_vn;
        }
        $listdirector = array();
        foreach ($directors as $a) {
            $listdirector[] = $a->name_vn;
        }

        $listcountry = array();
        foreach ($countries as $c) {
            $listcountry[] = $c->name;
        }
        $listtag = array();
        foreach ($tags as $t) {
            $listtag[] = $t->name;
        }
// Uncomment the following line if AJAX validation is needed
//        $this->performAjaxValidation($model);
        if (isset($_POST['Film'])) {
            $model->attributes = $_POST['Film'];
            $model->create_at = date("Y-m-d H:i:s");
            $model->user_create = Yii::app()->user->id;
            $model->link = Format::convertToSlug($model->name_vn);
            $director = Director::model()->find('name_vn=:name', array(':name' => $model->director));
            if (!$director) {
                $director = new Director();
                $director->name_vn = $model->director;
                $director->name_en = $model->director;
                $director->link = Format::convertToSlug($model->director);
                $director->insert();
            }
            $model->director_id = $director->id;
            if ($model->validate() && $model->insert()) {
                $actors = $model->actor;
                $list = (explode(',', $actors));
                foreach ($list as $ac) {
                    $search = Actor::model()->find("name_vn=:name", array(':name' => $ac));
                    if (!$search) {
                        $search = new Actor();
                        $search->name_vn = $ac;
                        $search->name_en = $ac;
                        $search->link = Format::convertToSlug($ac);
                        $search->insert();
                    }
                    $ac_film = new FilmActor();
                    $ac_film->film_id = $model->id;
                    $ac_film->actor_id = $search->id;
                    $ac_film->insert();
                }

                $tags = $model->tag;
                $list = (explode(',', $tags));
                foreach ($list as $t) {
                    $search = Tag::model()->find("name=:name", array(':name' => $t));
                    if (!$search) {
                        $search = new Tag();
                        $search->name = $t;
                        $search->link = Format::convertToSlug($t);
                        $search->insert();
                    }
                    $tag_film = new FilmTag();
                    $tag_film->film_id = $model->id;
                    $tag_film->tag_id = $search->id;
                    $tag_film->insert();
                }

                $countries = $model->country;
                $listcountry = (explode(',', $countries));
                foreach ($listcountry as $ct) {
                    $search = Country::model()->find("name=:name", array(':name' => $ct));
                    if (!$search) {
                        $search = new Country();
                        $search->name = $ct;
                        $search->link = Format::convertToSlug($ct);
                        $search->insert();
                    }
                    $ct_film = new FilmCountry();
                    $ct_film->film_id = $model->id;
                    $ct_film->country_id = $search->id;
                    $ct_film->insert();
                }

                foreach ($model->genre as $menu_id) {
                    $film_genre = new FilmGenre();
                    $film_genre->film_id = $model->id;
                    $film_genre->menu_id = $menu_id;
                    $film_genre->insert();
                }

                for ($i = 0; $i < $model->no_episode; $i++) {
                    $episode = new Episode();
                    $episode->name_en = $model->name_en;
                    $episode->name_vn = $model->name_vn;
                    $episode->film_id = $model->id;
                    $episode->link = Format::convertToSlug($model->name_vn . ' Tập ' . ($i + 1));
                    $episode->local_id = 1;
                    $episode->no_episode = $i + 1;
                    $episode->status = 0;
                    $episode->insert();
                }

                $this->redirect(array('view', 'id' => $model->id));
            }
        }
        $this->render('create', array(
            'model' => $model,
            'filmgenre' => $filmgenre,
            'actors' => $listactor,
            'directors' => $listdirector,
            'countries' => $listcountry,
            'tags' => $listtag,
            'genres' => $genres
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);
        $countries = Country::model()->findAll("status=1");
        $actors = Actor::model()->findAll("status=1");
        $directors = Director::model()->findAll("status=1");
        $genres = Menu::model()->findAll('parent_id >0 and status=1');
        $tags = Tag::model()->findAll("status=1");
        $listactor = array();
        foreach ($actors as $a) {
            $listactor[] = $a->name_vn;
        }
        $listdirector = array();
        foreach ($directors as $a) {
            $listdirector[] = $a->name_vn;
        }

        $listcountry = array();
        foreach ($countries as $c) {
            $listcountry[] = $c->name;
        }
        $listtag = array();
        foreach ($tags as $t) {
            $listtag[] = $t->name;
        }
        if ($model->actors) {
            $data = array();
            foreach ($model->actors as $ac) {
                $data[] = $ac->name_vn;
            }
            $model->actor = implode(",", $data);
        }
        if ($model->countries) {
            $data = array();
            foreach ($model->countries as $ct) {
                $data[] = $ct->name;
            }
            $model->country = implode(",", $data);
        }
        if ($model->tags) {
            $data = array();
            foreach ($model->tags as $tg) {
                $data[] = $tg->name;
            }
            $model->tag = implode(",", $data);
        }
        if ($model->menus) {
            foreach ($model->menus as $value) {
                $model->genre[] = $value->id;
            }
        }
        $director = Director::model()->find('id=:id', array(':id' => $model->director_id));
        $model->director = $director->name_vn;

// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);

        if (isset($_POST['Film'])) {
            $model->attributes = $_POST['Film'];
            $director = Director::model()->find('name_vn=:name', array(':name' => $model->director));
            if (!$director) {
                $director = new Director();
                $director->name_vn = $model->director;
                $director->name_en = $model->director;
                $director->link = Format::convertToSlug($model->director);
                $director->insert();
            }
            $model->director_id = $director->id;
            if ($model->validate() && $model->save()) {
                $film_ac = FilmActor::model()->findAll('film_id=' . $model->id);
                if ($film_ac) {
                    foreach ($film_ac as $fc) {
                        $fc->delete();
                    }
                }
                $actors = $model->actor;
                $list = (explode(',', $actors));
                foreach ($list as $ac) {
                    $search = Actor::model()->find("name_vn=:name", array(':name' => $ac));
                    if (!$search) {
                        $search = new Actor();
                        $search->name_vn = $ac;
                        $search->name_en = $ac;
                        $search->link = Format::convertToSlug($ac);
                        $search->insert();
                    }
                    $ac_film = new FilmActor();
                    $ac_film->film_id = $model->id;
                    $ac_film->actor_id = $search->id;
                    $ac_film->insert();
                }

                $film_tag = FilmTag::model()->findAll('film_id=' . $model->id);
                if ($film_tag) {
                    foreach ($film_tag as $ft) {
                        $ft->delete();
                    }
                }

                $tags = $model->tag;
                $list = (explode(',', $tags));
                foreach ($list as $t) {
                    $search = Tag::model()->find("name=:name", array(':name' => $t));
                    if (!$search) {
                        $search = new Tag();
                        $search->name = $t;
                        $search->link = Format::convertToSlug($t);
                        $search->insert();
                    }
                    $tag_film = new FilmTag();
                    $tag_film->film_id = $model->id;
                    $tag_film->tag_id = $search->id;
                    $tag_film->insert();
                }

                $film_country = FilmCountry::model()->findAll('film_id=' . $model->id);
                if ($film_country) {
                    foreach ($film_country as $fc) {
                        $fc->delete();
                    }
                }

                $countries = $model->country;
                $listcountry = (explode(',', $countries));
                foreach ($listcountry as $ct) {
                    $search = Country::model()->find("name=:name", array(':name' => $ct));
                    if (!$search) {
                        $search = new Country();
                        $search->name = $ct;
                        $search->link = Format::convertToSlug($ct);
                        $search->insert();
                    }
                    $ct_film = new FilmCountry();
                    $ct_film->film_id = $model->id;
                    $ct_film->country_id = $search->id;
                    $ct_film->insert();
                }
                $film_genre = FilmGenre::model()->findAll('film_id=' . $model->id);
                if ($film_genre) {
                    foreach ($film_genre as $fg) {
                        $fg->delete();
                    }
                }
                if ($model->genre) {
                    foreach ($model->genre as $menu_id) {
                        $film_genre = new FilmGenre();
                        $film_genre->film_id = $model->id;
                        $film_genre->menu_id = $menu_id;
                        $film_genre->insert();
                    }
                }
                $this->redirect(array('view', 'id' => $model->id));
            }
        }

        $this->render('update', array(
            'model' => $model,
            'actors' => $listactor,
            'directors' => $listdirector,
            'countries' => $listcountry,
            'tags' => $listtag,
            'genres' => $genres
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
// we only allow deletion via POST request
            $this->loadModel($id)->delete();

// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $this->redirect(array('admin'));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Film('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Film']))
            $model->attributes = $_GET['Film'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = Film::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'film-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
